package com.suxin.test.netty.adv.server;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.ImmediateEventExecutor;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Author: tang
 * @Description:
 * @Date 2025/1/21 18:05
 */
@Slf4j
public class MetricsHandler extends ChannelDuplexHandler {

    private final DefaultChannelGroup defaultChannelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);

    private static ScheduledExecutorService statService = new ScheduledThreadPoolExecutor(1);

    private static AtomicBoolean startTask = new AtomicBoolean(false);

    private static AtomicLong chCount = new AtomicLong(0);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        chCount.incrementAndGet();
        if (startTask.compareAndSet(false, true)) {
            statService.scheduleAtFixedRate(() -> {
                log.info("----------------性能指标采集开始-------------------");
                /*目前有多少在线Channel*/
                log.info("目前在线Channel数：" + chCount.get());
            }, 1, 5, TimeUnit.SECONDS);
        }
        defaultChannelGroup.add(ctx.channel());
        super.channelActive(ctx);
    }

}
